<?php session_start();
include("userfunctions.php");
include("../dbconnect.php");
// Todo: write code if isset($_POST['city']) == false
	if (isset($_POST['city']) && isset($_POST['country']) && isset($_POST['prename']) && isset($_POST['name']) && isset($_POST['password']) && isset($_POST['username'])){
		$query = sprintf("Select * from Person where Username ='%s'",
		$db->real_escape_string($_POST['username']));
		$result = $db->query($query);
		$row = $result->fetch_assoc();
		if (!isset($row['Username'])){
			$query2 = sprintf("Select * from City where CityName ='%s'",
			$db->real_escape_string($_POST['city']));
			$result2 = $db->query($query2);
			$row2 = $result2->fetch_assoc();
			if (!isset($row2['CityId'])){
				$query3 = sprintf("Insert into City set CityName ='%s'",
				$db->real_escape_string($_POST['city']));
				$db->query($query3);
				
				$query2 = sprintf("Select * from City where CityName ='%s'",
				$db->real_escape_string($_POST['city']));
				$result2 = $db->query($query2);
				$row2 = $result2->fetch_assoc();
			}
			$query2 = sprintf("Insert into Person (Username, Name, Firstname, CountryId, CityId, Password, Activated, OwnAccount) values ('%s', '%s', '%s', %d, %d, '%s', %b, %b)",
			$db->real_escape_string($_POST['username']), $db->real_escape_string($_POST['name']), $db->real_escape_string($_POST['prename']), $_POST['country'], $row2['CityId'], md5($_POST['password']), 0, 1);
			$db->query($query2);
			
			$query = sprintf("Select * from Person where Username ='%s'",
			$db->real_escape_string($_POST['username']));
			$result = $db->query($query);
			$row = $result->fetch_assoc();
			if (isset($row['Username'])){
				$_SESSION['PersonId'] = $row['PeId'];
				header ("Location:../../signuppart2.php");
			}else{
				echo "<script type=\"text/javascript\"> alert(\"A field is empty or wrong filled out\")</script>";
				header ("Location:../../signup.php");	
			}
			
		}else{
			echo "<script type=\"text/javascript\"> alert(\"This username is already in use\")</script>";
			header ("Location:../../signup.php");	
		}
	
	}else{
		echo "<script type=\"text/javascript\"> alert(\"A field is empty or wrong filled out\")</script>";
		header ("Location:../../signup.php");	
	}
?>